﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using DACU.Player;
using DACU.Player.Enums;
using DACU.Tools;
using DACU.VkontakteApi;
using Microsoft.Win32;

namespace DACU.Windows
{
	/// <summary>
	/// Логика взаимодействия для AddTrackWindow.xaml
	/// </summary>
	public partial class AddTrackWindow : Window
	{
		private bool _isSuccess;
		private Track _track;
		public Track Track
		{
			get { return _track; }
		}

		private Playlist _playlist = new Playlist();
		public Playlist Playlist
		{
			get { return _playlist; }
		}

		private TrackType _type;

		public AddTrackWindow()
		{
			InitializeComponent();
		}

		public AddTrackWindow(Window owner)
		{
			Owner = owner;
			InitializeComponent();
		}

		void SwitchShow(TrackType type)
		{
			_type = type;
			switch (type)
			{
				case TrackType.VKontakte:
					ListRow.Height = new GridLength(500);
					SizeToContent = SizeToContent.Width;
					NameRow.Height = FileRow.Height = new GridLength(0);
					LoadVKAudioCollection();
					break;
				case TrackType.File:
					FileRow.Height = GridLength.Auto;
					NameRow.Height = ListRow.Height = new GridLength(0);
					tbPath.IsEnabled = false;
					ResizeMode = ResizeMode.NoResize;
					MaxWidth = 600;
					break;
				case TrackType.Url:
					NameRow.Height = FileRow.Height = GridLength.Auto;
					ListRow.Height = new GridLength(0);
					bBrowse.Visibility = Visibility.Collapsed;
					Grid.SetColumnSpan(tbPath, 2);
					var marg = tbPath.Margin;
					marg.Left = 5;
					tbPath.Margin = marg;
					ResizeMode = ResizeMode.NoResize;
					MaxWidth = 600;
					break;
				default:
					FileRow.Height = NameRow.Height = ListRow.Height = new GridLength(0);
					bOk.Margin = new Thickness(5);
					break;
			}
		}

		public void Show(TrackType type)
		{
			SwitchShow(type);
			Show();
		}

		public bool? ShowDialog(TrackType type)
		{
			SwitchShow(type);
			ShowDialog();
			return _isSuccess;
		}

		void LoadVKAudioCollection()
		{
			var audios = VKApi.GetAudioCollection();
			var playlist = Playlist.FromVKAudioCollection(audios);
			dgVKAudios.ItemsSource = playlist;
		}

		private void bBrowse_Click(object sender, RoutedEventArgs e)
		{
			var dialog = new OpenFileDialog
			             	{
			             		Filter = "All Supported|"+SupportedFormats.All.GetPatterned()+"|" +
			             		         "MPEG Audio|*.mp3;*.mp2;*.mp1|" +
			             		         "Aiff|*.aiff|" +
			             		         "Ogg Vorbis|*.ogg|" +
			             		         "Windows wave|*.wav|" +
			             		         "MOD music|*.xm;*.it;*.s3m;*.mod;*.mtm;*.umx|" +
			             		         "MO3 music|*.mp3;*.ogg",
			             		Multiselect = true
			             	};
			bool? showDialog = dialog.ShowDialog(this);
			if (showDialog != null && showDialog.Value)
			{
				var sb = new StringBuilder();
				if (dialog.FileNames != null && dialog.FileNames.Length > 1)
				{
					int length = dialog.FileNames.Length;
					for (int i = 0; i < length; i++)
					{
						sb.AppendFormat("\"{0}\" ", dialog.SafeFileNames[i]);
						_playlist.Add(new Track { Path = dialog.FileNames[i], Type = TrackType.File });
					}
				}
				else
				{
					_playlist.Add(new Track {Path = dialog.FileName, Type = TrackType.File});
					sb.Append(dialog.FileName);
				}
				tbPath.Text = sb.ToString();
			}
		}

		void VKontakteSave()
		{
			if (dgVKAudios.SelectedItems != null && dgVKAudios.SelectedItems.Count > 0)
			{
				_playlist.Clear();
				_playlist.AddRange(dgVKAudios.SelectedItems.Cast<Track>());
			}
			else _playlist = null;
		}

		bool FileSave()
		{
			if(_playlist.IsEmpty) return false;
			_playlist.ForEach(track => track.GetInfoFromFile());
			return true;
		}

		bool UrlSave()
		{
			bool isOk = true;
			if (!String.IsNullOrWhiteSpace(tbPath.Text))
			{
				Uri url;
				try
				{
					url = new Uri(tbPath.Text);
					if (_track == null)
						_track = new Track { Type = TrackType.Url, Path = url.ToString() };
					else
						_track.Type = TrackType.Url;
					if (String.IsNullOrWhiteSpace(tbUrlTitle.Text))
					{
						NameRow.Height = GridLength.Auto;
						tbUrlTitle.Focus();
						isOk = false;
					}
					else
						_track.Title = tbUrlTitle.Text;
				}
				catch(UriFormatException)
				{
					isOk = false;
					tbPath.Focus();
					_track = null;
				}
			}
			else isOk = false;
			return isOk;
		}

		private void Ok_Click(object sender, RoutedEventArgs e)
		{
			switch (_type)
			{
				case TrackType.VKontakte:
					VKontakteSave();
					_isSuccess = true;
					break;
				case TrackType.File:
					_isSuccess = FileSave();
					if(!_isSuccess)return;
					break;
				case TrackType.Url:
					_isSuccess = UrlSave();
					if (!_isSuccess) return;
					break;
			}
			Close();
		}

		private void cbSelectAll_Click(object sender, RoutedEventArgs e)
		{
			if (cbSelectAll.IsChecked ?? false)
				dgVKAudios.SelectAll();
			else
				dgVKAudios.SelectedItem = null;
		}

		//private void lbVKAudios_SelectionChanged(object sender, SelectionChangedEventArgs e)
		//{
		//    if (lbVKAudios.SelectedItems == null || lbVKAudios.SelectedItems.Count < 1)
		//    {
		//        cbSelectAll.IsChecked = false;
		//        return;
		//    }
		//    if (lbVKAudios.SelectedItems.Count < lbVKAudios.Items.Count)
		//        cbSelectAll.IsChecked = null;
		//    else
		//        cbSelectAll.IsChecked = true;
		//}

		private void tbPath_GotFocus(object sender, RoutedEventArgs e)
		{
			(sender as TextBox).SelectAll();
			(sender as TextBox).ReleaseMouseCapture();
		}

		private void Window_ContentRendered(object sender, EventArgs e)
		{
			if (_type == TrackType.VKontakte)
				ListRow.Height = new GridLength(1,GridUnitType.Star);
		}

		private void dgVKAudios_SelectionChanged(object sender, SelectionChangedEventArgs e)
		{
			if (dgVKAudios.SelectedItems == null || dgVKAudios.SelectedItems.Count < 1)
			{
				cbSelectAll.IsChecked = false;
				return;
			}
			if (dgVKAudios.SelectedItems.Count < dgVKAudios.Items.Count)
				cbSelectAll.IsChecked = null;
			else
				cbSelectAll.IsChecked = true;
		}
	}
}
